package net.jsoft.platform.core.web;

import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

import com.alibaba.fastjson.JSON;

import net.jsoft.platform.core.vo.resp.ResponseVO;
import net.jsoft.platform.security.entity.user.SysUser;

/**
 * Created by JOHN_ZHAO on 2016-05-20.
 */
@Controller
public class BaseController
{

    protected Logger logger = LogManager.getLogger();

    protected ResponseVO vo = new ResponseVO();

    @Autowired
    private MessageSource messageSource;

    @Resource(name = "mysqlJdbcTemplate")
    private JdbcTemplate template;

    // @Autowired
    // private HttpServletRequest request;

    // @Autowired
    // private HttpServletResponse response;

    public void outJsonObj(Object obj) throws Exception
    {
        HttpServletResponse response = ((ServletWebRequest) RequestContextHolder.getRequestAttributes()).getResponse();
        response.setCharacterEncoding("utf-8");
        if (obj != null)
        {
            // JSONUtils.valueToString(arg0)
            response.getWriter().write(JSON.toJSONString(obj));
        }
        response.getWriter().flush();
    }

    public JdbcTemplate getTemplate()
    {
        return template;
    }

    public void setTemplate(JdbcTemplate template)
    {
        this.template = template;
    }

    public void outString(String str) throws Exception
    {
        HttpServletResponse response = ((ServletWebRequest) RequestContextHolder.getRequestAttributes()).getResponse();
        response.setCharacterEncoding("utf-8");
        if (StringUtils.isNotEmpty(str))
        {
            response.getWriter().write(str);
        }
        response.getWriter().flush();
    }

    public String getI18nMsg(String key)
    {
        Object[] arg = null; // 替换变量参数
        return messageSource.getMessage(key, arg, Locale.getDefault());
    }

    public HttpServletRequest getRequest()
    {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public HttpServletResponse getResponse()
    {
        HttpServletResponse response = ((ServletWebRequest) RequestContextHolder.getRequestAttributes()).getResponse();
        return response;
    }

    public void outSuccess(String message) throws Exception
    {
        vo.setFlag(ResponseVO.SUCCESS);
        vo.setMessage(message);
        this.outJsonObj(vo);
    }

    public void outFail(String message) throws Exception
    {
        vo.setFlag(ResponseVO.FAIL);
        vo.setMessage(message);
        outJsonObj(vo);
    }

    /**
     * SecurityContext securityContextImpl = this.getSecurityContext();
        // 登录名  
        System.out.println("Username:" + securityContextImpl.getAuthentication().getName());
        // 登录密码，未加密的  
        System.out.println("Credentials:" + securityContextImpl.getAuthentication().getCredentials());
        WebAuthenticationDetails details = (WebAuthenticationDetails) securityContextImpl.getAuthentication().getDetails();
        // 获得访问地址  
        System.out.println("RemoteAddress" + details.getRemoteAddress());
        // 获得sessionid  
        System.out.println("SessionId" + details.getSessionId());
        // 获得当前用户所拥有的权限  
        List<GrantedAuthority> authorities = (List<GrantedAuthority>) securityContextImpl.getAuthentication().getAuthorities();
        for (GrantedAuthority grantedAuthority : authorities)
        {
            System.out.println("Authority" + grantedAuthority.getAuthority());
        }
     * @return
     */
    public SecurityContext getSecurityContext()
    {
        return (SecurityContext) this.getRequest().getSession().getAttribute("SPRING_SECURITY_CONTEXT");
    }

    public SysUser getUser()
    {
        Authentication au;
        SecurityContext ctx = this.getSecurityContext();
        SysUser user = null;
        if (ctx != null)
        {
            au = ctx.getAuthentication();
            user = (SysUser) au.getPrincipal();
        }
        return user;
    }

    public void saveIndexUIInSession(String path)
    {
        this.getUser().setIndexPage(path);
    }

    public String getRealPath(String fileName)
    {
        WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        ServletContext servletContext = webApplicationContext.getServletContext();
        // 得到文件绝对路径
        String realPath = servletContext.getRealPath(fileName);

        return realPath;
    }

}
